package com.lsm.sm.dao.impl;

import java.io.Serializable;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.springframework.context.annotation.Scope;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.lsm.sm.dao.BaseDao;
import com.lsm.sm.entity.Model;

@Scope("prototype")
@Repository("baseDao")
public class BaseDaoImpl implements BaseDao{
	protected HibernateTemplate template;
	
	
	@Override
	public <T> T get( Class<T> clazz, Serializable id ){
		return (T)template.get( clazz, id );
	}
	
	@Override
	public <T> T get( final T t ){
		return (T)template.execute(new HibernateCallback<T>(){
			@SuppressWarnings("unchecked")
			public T doInHibernate( Session session ){
				Criteria criteria = session.createCriteria( t.getClass() );
				criteria.add( Example.create( t ) );
				return (T)criteria.uniqueResult();
			}
		});
	}
	
	public void update(Object obj ){
		template.update( obj );
	}
	
	@Resource(name="sessionFactory")
	public void setSessionFactory(SessionFactory sessionFactory) {
		template = new HibernateTemplate( sessionFactory );
	}
	
	@Transactional
	public void save( Model model ){
		Integer id = (Integer) template.save( model );
		model.setId( id );
	}
}
